package edu.neu.cloud_factory.controller;


import com.alibaba.fastjson.JSONObject;
import edu.neu.cloud_factory.entity.po.Factory;
import edu.neu.cloud_factory.entity.po.User;
import edu.neu.cloud_factory.service.FactoryService;
import edu.neu.cloud_factory.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 工厂 前端控制器
 * 没有增，删，改，因为增删改均和用户有关，在 User 控制器里面
 * 只有查，以及关停开启
 * </p>
 *
 * @author halozhy
 * @since 2021-07-15
 */
@RestController
@RequestMapping("/api/fac")
public class FactoryController {
    @Autowired
    FactoryService factoryService;

    @Autowired
    UserService userService;

    @GetMapping("/getById")
    public Factory getFacById(int facId) {
        return factoryService.getById(facId);
    }

    @PostMapping("/list")
    public JSONObject list(@RequestBody String CONTENT) {
        JSONObject j = JSONObject.parseObject(CONTENT);
        return factoryService.listFac(
                j.getInteger("page"),
                j.getInteger("limit"),
                j.getString("id"),
                j.getString("name"),
                j.getString("describe")
        );
    }

    /**
     * 关停工厂
     *
     * @param CONTENT
     * @return 0 ok -1 无此工厂 -2 此工厂已经被关停
     */
    @PostMapping("/shutdown")
    public int shutdown(@RequestBody String CONTENT) {
        JSONObject j = JSONObject.parseObject(CONTENT);
        return factoryService.shutdown(j.getInteger("id"));
    }

    /**
     * 开启工厂
     *
     * @param CONTENT
     * @return 0 ok -1 无此工厂 -2 此工厂已经是开启状态
     */
    @PostMapping("/open")
    public int open(@RequestBody String CONTENT) {
        JSONObject j = JSONObject.parseObject(CONTENT);
        return factoryService.open(j.getInteger("id"));
    }

    @GetMapping("/is_open")
    public int isOpen(long userId) {
        User u = userService.getById(userId);
        Factory f = factoryService.getById(u.getUFactoryId());
        if (f.getFState().equals("关停")) {
            return -1;
        }
        return 0;
    }
}

